//引入类
import Snake from "./Snake";
import ScorePanel from "./ScorePanel";
import Food from "./Food";

//控制器类
class GameControl{
    snake:Snake;
    food:Food;
    scorePanel:ScorePanel;
    //按键方向
    direction:string;
    //蛇是否活着
    isLive = true;
    constructor() {
       // 实例
        this.scorePanel = new ScorePanel()
        this.snake = new Snake();
        this.food = new Food();
        this.init()
    }
    //游戏开始
    init(){
        //绑定键盘监听事件
        document.addEventListener("keydown",this.keyDownHandler.bind(this)) //改变this指向
        //使蛇运动
        this. run()
    }
    //创建键盘按下去的响应函数
    keyDownHandler(event) {
        switch (event.key) {
            case "ArrowLeft":
                this.direction = 'left';
                break;
            case "Left":
                this.direction = 'left';
                break;
            case "ArrowDown":
                this.direction = 'down';
                break;
            case "Down":
                this.direction = 'down';
                break;
            case "ArrowUp":
                this.direction = 'up';
                break;
            case "Up":
                this.direction = 'up';
                break;
            case "ArrowRight":
                this.direction = 'right';
                break;
            case "Right":
                this.direction = 'right';
                break;
        }
    }
    //蛇移动的方法
    run(){
        let X = this.snake.X;
        let Y = this.snake.Y
        switch (this.direction) {
            case 'left':
                X-=10;
                break;
            case 'right':
                X+=10
                break;
            case 'up':
                Y-=10
                break;
            case 'down':
                Y+=10
                break;
        }
        //是否吃到食物
        this.check(X,Y)
        try{
            this.snake.X = X
            this.snake.Y = Y
        }catch (e){
            alert(e+'游戏结束！')
            this.isLive = false
        }

        //开启定时器
        this.isLive && setTimeout(this.run.bind(this),300-(this.scorePanel.level-1)*30)
    }
    //检查是否吃到食物
    check(X:number,Y:number){
        if(X ===this.food.X && Y ===this.food.Y){
            //食物改变位置
            this.food.change()
            //分数增加
            this.scorePanel.addScore()
            //蛇加一节
            this.snake.addBody()
        }
    }


}
export default  GameControl